#!/usr/bin/env ruby

require 'optparse'
require 'fileutils'

$app_dir      = File.expand_path('..', __FILE__)
$base_dir     = File.join($app_dir, 'current')

$options      = {env: 'production'}

FileUtils.mkdir $base_dir unless File.exist? $base_dir



module AppServer
  class << self
    def start
      system("bundle exec puma -C #{File.join($app_dir, 'config/puma.rb')}")
    end

    def restart
      system("kill -SIGUSR2 #{pid}")
    end

    def shutdown
      system("kill -TERM #{pid}")
    end

    def pid
      @pid ||= IO.read(pid_file).to_i
    end

    def pid_file
      @pid_file ||= File.join($base_dir, 'catlog.pid')
    end

    def stat
      @stat ||= IO.read(File.join($base_dir, 'catlog.state'))
    end
  end
end



OptionParser.new do |opts|
  opts.on('-a', '--all') do
    $options[:all] = true
  end
  opts.on('-e', '--env') do |value|
    $options[:env] = value
  end
end.parse!


case ARGV[0]
  when 'start'
    AppServer.start
    puts 'OK.'
  when 'restart'
    AppServer.restart
    puts 'Restart successfully.'
  when 'stop'
    AppServer.shutdown
    puts 'Done.All has been stopped.'
  when 'state'
    puts '====================================='
    puts "Application Server PID: #{AppServer.pid}"
    puts '====================================='
end